package net.lab1024.smartadmin.module.support.quartz.task.run;

import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.bean.WxCpDepart;
import me.chanjar.weixin.cp.bean.WxCpUser;
import net.lab1024.smartadmin.common.domain.ITask;
import net.lab1024.smartadmin.common.weixin.WxCpConfiguration;
import net.lab1024.smartadmin.constant.CommonConst;
import net.lab1024.smartadmin.module.system.department.DepartmentDao;
import net.lab1024.smartadmin.module.system.department.domain.dto.DepartmentVO;
import net.lab1024.smartadmin.module.system.department.domain.entity.DepartmentEntity;
import net.lab1024.smartadmin.module.system.employee.EmployeeDao;
import net.lab1024.smartadmin.module.system.employee.domain.dto.CpUserDTO;
import net.lab1024.smartadmin.module.system.position.PositionService;
import net.lab1024.smartadmin.module.system.position.domain.dto.PositionRelationAddDTO;
import net.lab1024.smartadmin.module.system.role.basic.RoleService;
import net.lab1024.smartadmin.module.system.role.basic.domain.dto.RoleAddDTO;
import net.lab1024.smartadmin.module.system.role.roleemployee.RoleEmployeeDao;
import net.lab1024.smartadmin.module.system.role.roleemployee.domain.RoleEmployeeEntity;
import net.lab1024.smartadmin.module.system.systemconfig.SystemConfigService;
import net.lab1024.smartadmin.module.system.systemconfig.constant.SystemConfigEnum;
import net.lab1024.smartadmin.util.SmartBeanUtil;
import net.lab1024.smartadmin.util.SmartDateUtil;
import net.lab1024.smartadmin.util.SmartDigestUtil;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * [ 同步员工信息 ]
 *
 * @author 五千
 * @version 1.0
 * @company 1024lab.net
 * @copyright (c) 2018 1024lab.netInc. All rights reserved.
 * @date 2021/3/24 0013 下午 14:26
 * @since JDK1.8
 */
@Slf4j
@Component("cpUserTask")
public class cpUser implements ITask {
    @Autowired
    private SystemConfigService systemConfigService;

    @Autowired
    private PositionService positionService;

    @Autowired
    private RoleEmployeeDao roleEmployeeDao;

    @Autowired
    private EmployeeDao employeeDao;

    @Autowired
    private DepartmentDao departmentDao;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void execute(String paramJson) throws Exception {

        Integer agentId = Integer.valueOf(systemConfigService.getCacheByKey(SystemConfigEnum.Key.CP_AGENTID).getConfigValue());
        WxCpService wxCpService = WxCpConfiguration.getCpService(agentId);

        //获取当前可见根们不id
        List<DepartmentVO> dList = departmentDao.listAll();
        if(dList.size()<=0){
            return ;
        }
        for(DepartmentVO dI : dList) {
            if(dI.getId() == 1 || dI.getId() == 99999){
                continue;
            }
            List<WxCpUser> list = wxCpService.getUserService().listByDepartment(dI.getId(), false, agentId);
            if(list == null){
                continue;
            }
            for (WxCpUser item : list) {
                CpUserDTO cpUserOld = employeeDao.getCpUserByUserId(item.getUserId());
                boolean isInsert = false;
                if (cpUserOld == null) {
                    isInsert = true;
                }
                CpUserDTO cpUserDTO = new CpUserDTO();
                cpUserDTO.setUserId(item.getUserId());
                cpUserDTO.setName(item.getName());
                cpUserDTO.setDepartId(item.getDepartIds()[0].longValue());
                cpUserDTO.setMobile(item.getMobile());
                cpUserDTO.setEmail(item.getEmail());
                cpUserDTO.setAvatar(item.getAvatar());
                cpUserDTO.setThumbAvatar(item.getThumbAvatar());
                cpUserDTO.setCreateUser(0L);
                try{
                    String openid = wxCpService.getUserService().userId2Openid(item.getUserId(), agentId).get("openid");
                    cpUserDTO.setOpenid(openid);
                }catch (Exception e){

                }

                if (isInsert) {
                    cpUserDTO.setLoginName(item.getName());
                    cpUserDTO.setLoginPwd(SmartDigestUtil.encryptPassword(CommonConst.Password.SALT_FORMAT, "123456"));
                    cpUserDTO.setIsDisabled(0);
                    employeeDao.insertCPUser(cpUserDTO);
                    //添加岗位关系
                    List<Long> postion = new ArrayList<>();
                    postion.add(18L);
                    PositionRelationAddDTO positionRelAddDTO = new PositionRelationAddDTO(postion, cpUserDTO.getId());
                    //存储所选岗位信息
                    positionService.addPositionRelation(positionRelAddDTO);

                    //更新角色 所有批量更新用户， 批量添加上默认角色
                    //roleEmployeeDao.deleteByEmployeeId(cpUserDTO.getId());
                    RoleEmployeeEntity roleEmployeeEntity = new RoleEmployeeEntity();
                    roleEmployeeEntity.setEmployeeId(cpUserDTO.getId());
                    roleEmployeeEntity.setRoleId(41L);
                    roleEmployeeDao.insert(roleEmployeeEntity);

                } else {
                    employeeDao.updateCPUser(cpUserDTO);
                }

                //判断是否角色丢失
                CpUserDTO cpsel = employeeDao.getCpUserByUserId(item.getUserId());
                List<Long> lroleId = roleEmployeeDao.selectRoleIdByEmployeeId(cpsel.getId());
                if(lroleId.size()<=0){
                    RoleEmployeeEntity roleEmployeeEntity = new RoleEmployeeEntity();
                    roleEmployeeEntity.setEmployeeId(cpsel.getId());
                    roleEmployeeEntity.setRoleId(41L);
                    roleEmployeeDao.insert(roleEmployeeEntity);
                }

            }
            log.debug(list.toString());
        }


//        for(WxCpDepart item:list){
//            DepartmentEntity departmentEntity = departmentDao.selectById(item.getId());
//
//            boolean isInsert = false;
//            if(departmentEntity == null ){
//                departmentEntity = new DepartmentEntity();
//                isInsert = true;
//            }
//            departmentEntity.setId(item.getId());
//            departmentEntity.setName(item.getName());
//            departmentEntity.setParentId(item.getParentId());
//            departmentEntity.setSort(item.getOrder());
//            departmentEntity.setUpdateTime(new Date());
//            if(isInsert){
//                //待主键插入数据；
//                departmentEntity.setCreateTime(new Date());
//                departmentDao.insertId(departmentEntity);
//            }else{
//                departmentDao.updateById(departmentEntity);
//            }
//        }
        log.warn("{}-今天搬了{}块砖,paramJson:{}", SmartDateUtil.formatYMDHMS(new Date()), System.currentTimeMillis(), paramJson);
    }
}
